package com.edais.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import com.edais.json.JSONException;
import com.edais.json.JSONObject;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;

/**
 * 工具类
 * 
 */
public class BaseHelper{
	private static final Logger logger = Logger.getLogger(BaseHelper.class);
    public static final String PARAM_EQUAL = "=";
    public static final String PARAM_AND   = "&";
    public static final String PARAM_MARK = "\"";
    public static final String PARAM_COLON = ":";
    public static final String PARAM_COMMA = ",";
    
    /**
     * 对Object进行List<NameValuePair>转换后按key进行升序排序，以key=value&...形式返回
     * 
     * @param list
     * @return
     */
    public static String sortParam(Object order)
    {
        List<NameValuePair> list = bean2Parameters(order);
        return sortParam(list);
    }
    
    /**
     * 将bean转换成键值对列表
     * 
     * @param bean
     * @return
     */
    public static List<NameValuePair> bean2Parameters(Object bean)
    {
        if (bean == null)
        {
            return null;
        }
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();

        // 取得bean所有public 方法
        Method[] Methods = bean.getClass().getMethods();
        for (Method method : Methods)
        {
            if (method != null && method.getName().startsWith("get")
                    && !method.getName().startsWith("getClass"))
            {
                // 得到属性的类名
                String value = "";
                // 得到属性值
                try
                {
                    String className = method.getReturnType().getSimpleName();
                    if (className.equalsIgnoreCase("int"))
                    {
                        int val = 0;
                        try
                        {
                            val = (Integer) method.invoke(bean);
                        } catch (InvocationTargetException e)
                        {
                        	logger.error("InvocationTargetException"+ e.getMessage());
                        }
                        value = String.valueOf(val);
                    } else if (className.equalsIgnoreCase("String"))
                    {
                        try
                        {
                            value = (String) method.invoke(bean);
                        } catch (InvocationTargetException e)
                        {
                            logger.error("InvocationTargetException"+ e.getMessage());
                        }
                    }
                    if (value != null && value != "")
                    {
                        // 添加参数
                        // 将方法名称转化为id，去除get，将方法首字母改为小写
                        String param = method.getName().replaceFirst("get", "");
                        if (param.length() > 0)
                        {
                            String first = String.valueOf(param.charAt(0))
                                    .toLowerCase();
                            param = first + param.substring(1);
                        }
                        parameters.add(new BasicNameValuePair(param, value));
                    }
                } catch (IllegalArgumentException e)
                {
                    logger.error("IllegalArgumentException"+ e.getMessage());
                } catch (IllegalAccessException e)
                {
                    logger.error("IllegalAccessException"+ e.getMessage());
                }
            }
        }
        return parameters;
    }
    
    /**
     * 对List<NameValuePair>按key进行升序排序，以key=value&...形式返回
     * 
     * @param list
     * @return
     */
    public static String sortParam(List<NameValuePair> list)
    {
        if (list == null)
        {
            return null;
        }
        Collections.sort(list, new Comparator<NameValuePair>(){
            @Override
            public int compare(NameValuePair lhs, NameValuePair rhs)
            {
                return lhs.getName().compareToIgnoreCase(rhs.getName());
            }
        });
        StringBuffer sb = new StringBuffer();
        for (NameValuePair nameVal : list)
        {
        	
            if (null != nameVal.getValue() && !"".equals(nameVal.getValue())
            		&& !nameVal.getName().equals("user_id")
            		&& !nameVal.getName().equals("force_bank")
            		&& !nameVal.getName().equals("id_type")
					&& !nameVal.getName().equals("id_no")
					&& !nameVal.getName().equals("acct_name")
					&& !nameVal.getName().equals("flag_modify")
					&& !nameVal.getName().equals("card_no")
					&& !nameVal.getName().equals("no_agree"))
            {
                sb.append(nameVal.getName());
                sb.append(PARAM_EQUAL);
                sb.append(nameVal.getValue());
                sb.append(PARAM_AND);
            }
        }
        String params = sb.toString();
        if (sb.toString().endsWith(PARAM_AND))
        {
            params = sb.substring(0, sb.length() - 1);
        }
        logger.debug("待签名串"+params);
        return params;
    }
    
    public static String toJSONString(Object obj)
    {
        JSONObject json = new JSONObject();
        try
        {
            List<NameValuePair> list = bean2Parameters(obj);
            for (NameValuePair nv : list)
            {
                json.put(nv.getName(), nv.getValue());
            }
        } catch (JSONException e)
        {
        	logger.error("BaseHelper类的toJSONString方法发生异常"+ e.getMessage());
        }
        return json.toString();
    }
    
    public static String sortJson(String jsonString) {

        List<NameValuePair> list = json2Parameters(jsonString);
        return sortJson(list);
    }
    public static List<NameValuePair> json2Parameters(String jsonString)
    {
        if (jsonString == null)
        {
            return null;
        }
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();

        try {
            JSONObject jsonObject = new JSONObject(jsonString);

            Iterator<String> keyIter = jsonObject.keys();

            String key;
            Object value;
            while (keyIter.hasNext()) {

                key = (String) keyIter.next();
                value = jsonObject.get(key);

                parameters.add(new BasicNameValuePair(key, value.toString()));

            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return parameters;
    }
    
    /**
     * 对List<NameValuePair>按key进行升序排序，
     * 
     * @param list
     * @return
     */
    public static String sortJson(List<NameValuePair> list)
    {
        if (list == null)
        {
            return null;
        }
        Collections.sort(list, new Comparator<NameValuePair>() {
            @Override
            public int compare(NameValuePair lhs, NameValuePair rhs)
            {
                return lhs.getName().compareToIgnoreCase(rhs.getName());
            }
        });
        StringBuffer sb = new StringBuffer();

        sb.append("{");
        for (NameValuePair nameVal : list)
        {

            {
                sb.append(PARAM_MARK);
                sb.append(nameVal.getName());
                sb.append(PARAM_MARK);
                sb.append(PARAM_COLON);
                sb.append(PARAM_MARK);
                sb.append(nameVal.getValue());
                sb.append(PARAM_MARK);
                sb.append(PARAM_COMMA);
            }
        }

        if (sb.toString().endsWith(PARAM_COMMA))
        {
            sb.deleteCharAt(sb.length() - 1);
        }
        sb.append("}");
        String params = sb.toString();
        return params;
    }
}